package com.basic.business.indicatorsFile.service.impl;

import com.basic.common.config.BasicConfig;
import com.basic.common.exception.file.InvalidExtensionException;
import com.basic.common.utils.SecurityUtils;
import com.basic.common.utils.file.FileUploadUtils;
import com.basic.common.utils.file.MimeTypeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.basic.common.core.service.impl.BaseServiceImpl;
import com.basic.business.indicatorsFile.domain.TIndicatorsFile;
import com.basic.business.indicatorsFile.service.ITIndicatorsFileService;
import com.basic.business.indicatorsFile.mapper.TIndicatorsFileMapper;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 指标数据文件管理Service业务层处理
 *
 * @author zhaoxy_jn@163.com
 */
@Service
public class TIndicatorsFileServiceImpl extends BaseServiceImpl<TIndicatorsFileMapper,TIndicatorsFile> implements ITIndicatorsFileService {

    @Resource
    private TIndicatorsFileMapper tIndicatorsFileMapper;

    @Override
    public int getCountByFileHash(String fileHash) {
        return tIndicatorsFileMapper.getCountByFileHash(fileHash);
    }

    @Override
    public List<TIndicatorsFile> getByFileHash(String fileHash) {
        return tIndicatorsFileMapper.getByFileHash(fileHash);
    }

    @Override
    public String uploadIndicatorsFile(MultipartFile file, Date selectDate, String storeId, String fileHash, Integer type) {
        try {
            String absolutePath = FileUploadUtils.upload(BasicConfig.getIndicatorsPath(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);

            //组装文件上传记录数据并存储
            TIndicatorsFile tIndicatorsFile = new TIndicatorsFile();
            tIndicatorsFile.setId(null);
            tIndicatorsFile.setStoreId(storeId);
            tIndicatorsFile.setFileName(file.getOriginalFilename());
            tIndicatorsFile.setSelectDate(selectDate);
            tIndicatorsFile.setAbsolutePath(absolutePath);
            tIndicatorsFile.setFileHash(fileHash);
            tIndicatorsFile.setType(type);
            tIndicatorsFile.setCreateBy(SecurityUtils.getUsername());
            tIndicatorsFile.setCreateTime(new Date());

            tIndicatorsFileMapper.insert(tIndicatorsFile);

            //返回文件id
            return tIndicatorsFile.getId();
        } catch (InvalidExtensionException | IOException e) {
            throw new RuntimeException(e);
        }
    }
}
